//
//  FriendChatSettingVC.m
//  AAIM
//
//  Created by awh on 2019/11/30.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "FriendChatSettingVC.h"
#import "StartGroupChatVC.h"
#import "ContactRequestLogic.h"
@interface FriendChatSettingVC ()
@property(nonatomic,strong)UIScrollView * bgScrollView;
@property(nonatomic,strong)CustomAlertView * alertView;
@property(nonatomic,strong)CustomAlertView * clearMessage_alertView;

@end

@implementation FriendChatSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}


-(void)initUI
{
    [self.view addSubview:self.bgScrollView];
    self.gk_navTitle=@"聊天设置";
    NSArray * btnName=@[@"置顶会话",@"消息免打扰",@"加入黑名单",@"清空聊天记录"];
    
    UIView * topbackV= [[UIView alloc]initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 95)];
    topbackV.backgroundColor=[UIColor whiteColor];
    [self.bgScrollView addSubview:topbackV];
    
    
    CGFloat btnWidth =(SCREEN_WIDTH-80-30)/5;
    for (int i=0; i<2; i++) {
        PublicButton * topButton=[[PublicButton alloc]initWithFrame:CGRectMake(15+(btnWidth+20)*i,10, btnWidth, 75) withButtonType:@"friendChatSetButton"];
        
        if (i==0) {
            topButton.titleLbl.text=_friendModel.nickname;
            topButton.iconImage.backgroundColor = [UIColor redColor];
            //            NSString * avatarstr;
            //            if ([_userAvatar containsString:@"http"]) {
            //                avatarstr=_userAvatar;
            //            }else
            //            {
            //            NSString * avatarstr=[NSString stringWithFormat:@"%@%@",userHeaderImage,_friendModel.head];
            //            }
            
            [topButton.iconImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,_friendModel.head]] placeholderImage:kHeadPlaceholderImage completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                
                topButton.iconImage.image = image;
            }];
            
        }else
        {
            topButton.iconImage.image=[UIImage imageNamed:@"会话设置-增加"];
            topButton.titleLbl.text=@"邀请";
            [topButton addTarget:self action:@selector(AddFriendsChatGroupAction) forControlEvents:UIControlEventTouchUpInside];
        }
        [topbackV addSubview:topButton];
    }
    
    for (int i=0; i<btnName.count; i++) {
        PublicButton * btn=[[PublicButton alloc]initWithFrame:CGRectMake(0, topbackV.bottom+10+(50+0)*i, SCREEN_WIDTH, 50) withButtonType:@"friendChatSetCellButton"];
        btn.backgroundColor=[UIColor whiteColor];
        btn.titleLbl.text=btnName[i];
        btn.tag=i+1;
        if (i>2) {
            btn.swicthButton.hidden=YES;
            [btn addTarget:self action:@selector(alertClearMessage) forControlEvents:UIControlEventTouchUpInside];
        }else if (i==2){
            btn.swicthButton.hidden=YES;
            [btn addTarget:self action:@selector(joinBlackList:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            
            btn.swicthButton.hidden=NO;
            btn.swicthButton.tag=i+1;
            [btn.swicthButton addTarget:self action:@selector(clickbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
        }
        if (i==3) {
            btn.y=topbackV.bottom+0+(50+10)*3;
            
        }
        
        [self.bgScrollView addSubview:btn];
    }
}

- (void)alertClearMessage {
    KWeakSelf;
    WS(ws);
    _clearMessage_alertView = [[CustomAlertView alloc] initWithFrame:self.view.bounds withType:@"3" title:@"确认清空消息记录"];
    _clearMessage_alertView.clickBlock = ^(NSString * _Nonnull selectType, NSString * _Nonnull textf, NSString * _Nonnull remarkStr) {
        if ([selectType isEqualToString:@"2"]) {
            [[ChatMessagesDataBase shareChatMessagesDataBase] clearAllMessagesWithUid:[weakSelf.friendModel.fuuid integerValue]];
            [[ConversationListDataBase shareConversationListDataBase] deleteConversationWithKeyid:[NSString stringWithFormat:@"friend_%@",weakSelf.friendModel.fuuid]];
            [[ConversationManager shareManager] deleteConversationWithKeyid:[NSString stringWithFormat:@"friend_%@",weakSelf.friendModel.fuuid]];
            [[ConversationManager shareManager] reloadData];
                 if (weakSelf.delegate) {
                   [weakSelf.delegate clearGroupChatHistory];
                       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                  [weakSelf showTipHudWithText:@"清空成功"];
                                    });
                              }
        }
        [ws.clearMessage_alertView removeFromSuperview];
    };
    
    [[UIApplication sharedApplication].keyWindow addSubview:_clearMessage_alertView];
}

- (void)joinBlackList:(UIButton *)sender{
    //加入黑名单
    WS(ws);
    KWeakSelf;
    _clearMessage_alertView = [[CustomAlertView alloc] initWithFrame:self.view.bounds withType:@"3" title:@"加入黑名单后，您将不再收到对方的消息"];
    _clearMessage_alertView.clickBlock = ^(NSString * _Nonnull selectType, NSString * _Nonnull textf, NSString * _Nonnull remarkStr) {
        if ([selectType isEqualToString:@"2"]) {
            //                      NSLog(@"点击了确定");
            [weakSelf showAlwaysTipHudWithText:@"请稍等"];
            [weakSelf requestJoinBlackListNet];
        }
        [ws.clearMessage_alertView removeFromSuperview];
    };
    
    [[UIApplication sharedApplication].keyWindow addSubview:_clearMessage_alertView];
}

- (void)requestJoinBlackListNet{
    KWeakSelf;
    [ContactRequestLogic requestJoinBlackListFriendWithFuuid:_friendModel.fuuid withBlock:@"1" withDescribe:@"" withRemark:@"" Success:^(NSDictionary * _Nonnull Dict) {
        [weakSelf hideHud];
        NSLog(@"拉黑好友：%@",Dict);
        NSLog(@"拉黑结果：%@",Dict[@"message"]);
        [[UserDataBaseTool shareUserDataBaseTool] deleteFriend:weakSelf.friendModel.fuuid];
        [[UserDataBaseTool shareUserDataBaseTool] reloadData:1 Success:^(BOOL isOK) {
            if (isOK) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemAddFriends object:nil];
            }
        }];
        [self showTipHudWithText:Dict[@"message"]];
    } failure:^(NSString * _Nonnull errMsg) {
        [weakSelf hideHud];
        [self showTipHudWithText:errMsg];
    }];
}

-(void)clickbuttonAction:(PublicButton*)sender
{
    sender.selected=!sender.selected;
    if (sender.tag == 1) {
        // 消息置顶
        [[ConversationListDataBase shareConversationListDataBase] updateConversationTopStatusWithChatType:ChatTypeFriend uidOrGroupId:[self.friendModel.fuuid integerValue] isTop:sender.isSelected];
    } else {
        // 消息免打扰
        [[ConversationListDataBase shareConversationListDataBase] updateMessageIgnoreStatusWithChatType:ChatTypeFriend uidOrGroupId:[self.friendModel.fuuid integerValue] isIgnore:sender.isSelected];
    }
    
}
-(void)AddFriendsChatGroupAction
{
    StartGroupChatVC * starVC= [[StartGroupChatVC alloc]init];
    starVC.type = 1;
    starVC.friendsFuuid = _friendModel.fuuid;
    [self.navigationController pushViewController:starVC animated:YES];
}

-(UIScrollView*)bgScrollView
{
    if (!_bgScrollView) {
        _bgScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,NavigationBarHeight, SCREEN_WIDTH,SCREEN_HEIGHT-NavigationBarHeight-EMVIEWBOTTOMMARGIN)];
        _bgScrollView.showsVerticalScrollIndicator=NO;
        _bgScrollView.showsHorizontalScrollIndicator=NO;
        _bgScrollView.backgroundColor=KHEXCOLOR(@"#F4F4F4");
        [_bgScrollView setContentSize:CGSizeMake(0, kScreenHeight)];
    }
    return _bgScrollView;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
